<template>
  <!-- 添加或修改隐患上报对话框 -->
  <el-dialog :title="title" :visible.sync="open" append-to-body @close="cancel" class="dialog-form">
    <el-form ref="form" :model="form" label-width="140px" v-if="isApprove">
      <el-row>
        <el-col v-for="(domain, index) in form.formData" :key="index" :span="domain.spanNum">
          <el-form-item :label="domain.controlLable" :prop="domain.controlField" :rules="domain.rules" v-if="domain.show">
            <el-input 
              v-if="'input' == domain.controlType"
              :model.trim="form[domain.controlField]" 
              clearable
            >
            </el-input>
            <el-input 
              v-if="'textarea' == domain.controlType"
              :maxlength="300" 
              show-word-limit 
              type="textarea" 
              :autosize="{ minRows: 2, maxRows: 10 }"
              v-model.trim="form[domain.controlField]" 
              clearable
            >
            </el-input>
            <el-date-picker 
              v-if="'date' == domain.controlType"
              v-model="form[domain.controlField]" 
              type="date" 
              value-format="yyyy-MM-dd" 
              placeholder="选择日期"
              clearable
              :picker-options="pickeroptions"
            >
            </el-date-picker>
            <el-input 
              v-if="'money' == domain.controlType"
              v-model.trim="form[domain.controlField]"  
              :maxlength="9"
              clearable
              show-word-limit>
              <template slot="append">元</template>
            </el-input>
            <el-select v-if="'select' == domain.controlType" v-model="form[domain.controlField]" clearable @change="(val) => handleSelChange(val,domain.controlField)">
              <el-option v-for="(item, index) in domain.options" :key="index" :label="item.dictLabel"
                :value="item.dictLabel">
                {{ item.dictLabel }}
              </el-option>
            </el-select>
            <el-radio-group v-model="form[domain.controlField]" v-if="'radio' == domain.controlType" clearable>
              <el-radio v-for="(item,index) in domain.options" :label="item.dictValue" 
              :key="index">
              {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
            <elUploads v-if="'upload' == domain.controlType" 
              :ref="'upload'"
              :action="action"
              :auto-upload="true"
              :limit="5"
              :fileList="fileList"
              :remove-file="removeFile"
              :accept="'.jpg,.jpeg,.gif,.png,.pdf,.docx'"
              :success-fun="(response, file, fileList) => success(response, file, fileList,index,domain.controlField)"
              :before-upload="uploadBeforeUpload"
              multiple 
              tip="提示：只能上传.jpg,.png,.jpeg,.gif,等图片(每张最大50M)和docx、pdf格式的文档,文件总计不超过5个">
            </elUploads>
          </el-form-item>
        </el-col>
      </el-row>      
    </el-form>
    <SubmitHistoryForm :info="info" :row="row" :imgs="imgLists" :key="timer"/>
    <div slot="footer" class="dialog-footer" v-if="isApprove">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { formDataShow, formDataSave } from "@/api/activiti/task";
import SubmitHistoryForm from "./submitHistoryForm.vue"
export default {
  props:['info','row'],
  components:{ SubmitHistoryForm },
  data() {
    return {
      routeName:this.$route.name,
      form: {},
      open:false,
      dangerLevelOptions:[],
      fileList:[],
      imgLists:[],
      action: process.env.VUE_APP_BASE_API + "/common/upload",
      title:'',
      // rules:{
      //   isDanger:[{required:true,message:'请确认是否为隐患',trigger:'change'}],
      //   level:[{required:true,message:'请选择隐患等级',trigger:'change'}],
      //   rectifyType:[{required:true,message:'请选择整改类型',trigger:'change'}],
      //   rectifyTime:[{required:true,message:'请选择整改时间',trigger:'change'}],
      //   rectifyAsk:[{required:true,message:'请输入整改要求',trigger:'blur'}],
      //   rectifyStartTime:[{required:true,message:'请选择整改开始时间',trigger:'change'}],
      //   rectifyEndTime:[{required:true,message:'请选择整改结束时间',trigger:'change'}],
      // },
      // pickeroptions:{
      //   disabledDate: (time) => {
      //     if (this.form.rectifyEndTime) {
      //       return time.getTime() > new Date(this.form.rectifyEndTime).getTime();
      //     }
      //   },
      // },

      pickerOptions:{},
      // 开始时间限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.form.rectifyEndTime) {
            return time.getTime() > new Date(this.form.rectifyEndTime).getTime();
          }
        },
      },
      // 结束时间限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if(this.form.rectifyStartTime){
            return time.getTime() < new Date(this.form.rectifyStartTime).getTime();
          }
        },
      },
      active:false,
      // 表单参数
      form: {
        formData: [],
      },
      // 表单校验
      rules: {},
      formData:[],
      activeIndex:'',
      controlField:'',
      isApprove:false,
      timer:'',
    }
  },
  watch:{
    info(newVal,oldVal){
      if(newVal!=oldVal){
        this.form = newVal;
        if(this.form.imgUrl){
          this.imgLists=(JSON.parse(this.form.imgUrl)??[]).map(_ => {
            return {
              ..._,
              url:process.env.VUE_APP_BASE_API+_.url,
            }
          });  
        }else{
          this.imgLists=[];
        }
      }
    },
  },
  created(){
    const statusOptions={
      'Confirm':'隐患确认',
      'Manage':'隐患治理与整改',
      'CheckAccept':'隐患验收与评估',
    };
    const { name } = this.$route;
    this.title=statusOptions[name]??'';
  },
  methods:{
    // 初始化
    init(row,type){
      console.log('this.taskId row',row,type); 
      this.timer=new Date().getTime();
      if(type==1){
        this.isApprove=true;
        this.getFormData(row.taskId);
      }else{
        this.isApprove=false;
      }
    },
    getFormData(taskId){
      formDataShow(taskId).then((response) => {
        // "FormProperty_isDanger--__!!radio--__!!是否确认隐患--__!!i--__!!是--__--否" 
        // "FormProperty_level--__!!select--__!!隐患等级--__!!f--__!!danger_level" 
        // "FormProperty_rectifyType--__!!select--__!!整改类型--__!!f--__!!rectify_type" 
        // "FormProperty_rectifyStartTime--__!!date--__!!整改开始时间--__!!f--__!!null" 
        // "FormProperty_rectifyEndTime--__!!date--__!!整改结束时间--__!!f__!!null"
        // "FormProperty_rectifyAsk--__!!textarea--__!!整改要求--__!!f--__!!null"
        let datas = response.data;
        let formData = [];
        for (let i = 0; i < datas.length; i++) {
          let strings = datas[i].split("--__!!");
          let options=[];
          let rules= [];
          let spanNum=12;
          let params={
            controlId: strings[0],
            controlType: strings[1],
            controlLable: strings[2],
            controlIsParam: strings[4],
            controlField: strings[0],
            controlValue: null,
            controlDefault: strings[4],
            show:true,
          };
          console.log('strings',strings);
          switch (strings[1]) {
            case "radio":
              let statusInfo = strings[4].split("--__--");
              options=statusInfo.map((_,index) => {
                return {
                  dictValue:(index+1).toString(),
                  dictLabel:_,
                }
              });
              spanNum=24;
              break;
            case "select":
              this.getDicts(strings[4]).then(response => {
                 this.form.formData[i].options=response.data;
              });
              break;
            case "textarea":
            case "upload":
              rules=[
                {
                  required: false,
                  message: strings[2] + "不能为空",
                  trigger: "change",
                },
              ],
              spanNum=24;
              break;
          };
          params={
            ...params,
            options:options,
            spanNum:spanNum,
          };
          let validateStartTime = (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择开始时间"));
            } else {
              if (this.form.endTime) {
                this.$refs.form.validateField('endTime');
              }
              callback();
            }
          };
          let validateEndTime = (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择结束时间"));
            } else {
              if (!this.form.beginTime) {
                callback(new Error("请选择开始时间！"))
              } else if (Date.parse(this.form.beginTime) > Date.parse(value)) {
                callback(new Error("结束时间必须大于开始时间！"))
              } else {
                callback();
              }
            }
          };
          if (strings[1] == "money") {
            const checkMoney = (rule, value, callback) => {
              let rex = /^([0-9]|[1-9]\d+)(\.\d{2})?$/
              if (value&&!rex.test(value)) {
                return callback(new Error('请输入不为负的数字，小数点后保留两位'));
              } else {
                callback();
              }
            };
            let moneyRules= [
                {
                  required: false,
                  validator: checkMoney,
                  trigger: ["blur", "change"],
                },
              ];
            // 添加金额的校验
            formData.push(
              {
                ...params,
                rules:moneyRules
              }
            )
          }else if(strings[1] == "upload"){
            formData.push({
              ...params,
              options:options,
              spanNum:spanNum,
              rules: [
                {
                  required: false,
                  message: strings[2] + "不能为空",
                  trigger: "change",
                },
              ],
            })
          }else if(strings[1] == "date"){     

            // console.log('strings[1]',strings[0])
            // formData.push({
            //   ...params,
            //   options:options,
            //   spanNum:spanNum,
            //   rules: [
            //     {
            //       required: true,
            //       // validator: checkMoney,
            //       trigger: "change",
            //     },
            //   ],
            // })
          }else{
            formData.push({
              ...params,
              options:options,
              spanNum:spanNum,
              rules: [
                {
                  required: true,
                  message: strings[2] + "不能为空",
                  trigger: "change",
                },
              ],
            })
          }
        };
        this.$set(this.form,'formData',formData);
        console.log('this.form', this.form.formData);
      })
    },
    handleSelChange(val,field) {
      console.log('val',val,field);
      if(field=='FormProperty_rectifyType'){
        if (val == '立即整改') {
          this.form.formData.forEach((element,index) => {
            console.log('elemetn',element);       
            if (element.controlType == "date") {
              this.$set(this.form.formData,index,{...element,show:false})
            }
          })        
          this.active = false;
        } else {
          this.active = true;
          this.form.formData.forEach((element,index) => {  
            if (element.controlType == "date") {
              this.$set(this.form.formData,index,{...element,show:true})
            }
          })
        }
      }
    },
    cancel(){
      this.open=false;
    },
    submitForm(){
      console.log('this.form',this.form.formData);
      console.log('this.formData',this.form.formData);
      console.log('this.fileList',this.fileList);


      // 对fileList 进行处理
      if(this.fileList&&this.fileList.length>0){
        let ls=this.fileList.map(_ => {
          return {
            url:_?.response?.fileName??_.url,
            name:_?.response?.oldFileName??_.name,
          }
        })
        this.form.formData[this.activeIndex].controlValue = JSON.stringify(ls);
        this.$set(this.form,this.controlField,JSON.stringify(ls));   
        console.log('this.form.formData',this.form.formData);  
      }
      this.form.formData=this.form.formData.filter(_ => _.show);
      this.$refs.form.validate(valid => {
        if(valid){
          Object.entries(this.form).forEach(([key, val]) => {
            this.form.formData.map((_) => {
              if (_.controlField == key) {
                _.controlValue = val
              }
              delete _.span,
              delete _.rules;
              delete _.options;
            })
          });
          formDataSave(
            this.row.taskId,
            this.form.formData,      
          ).then((response) => {
            if(response.code == 200){
              this.msgSuccess("审批成功");
              this.open = false;
              // 更新表单
              this.$emit('refresh')
            }
          });
        }
      })
    },
    handleExceed(files, fileList) {
      this.$message.error(`只允许上传单个文件`);
    },
    // 移除文件
    removeFile(file, fileList) {
      this.fileList = fileList;
    },
    // 上传文件
    success(response, file, fileList,index,field) {
      console.log('inini',response,fileList,index,field);
      this.activeIndex = index;
      this.controlField = field;
      this.fileList=fileList;
      console.log('this.fileList',this.fileList);
      
      if(fileList&&fileList.length>0){
        this.$refs.form.clearValidate(field);
        this.$message.success("上传成功！")
      }


      // if (response.code == 200) {
      //   let ls = fileList.map((element) => {
      //     return {
      //       url:element.response.fileName,
      //       name:element.response.oldFileName,
      //     }
      //   });
      //   this.form.formData[this.activeIndex].controlValue = JSON.stringify(ls);
      //   console.log('this.form.formData',this.form.formData);  
      //   this.$set(this.form,this.controlField,JSON.stringify(ls))
      //   this.$refs.form.validateField(this.controlField)
      //   this.$message.success("上传成功！")
      // }
    },
    uploadBeforeUpload(){

    },
  }
}
</script>
<style lang='scss' scoped>

</style>